# -*- coding:utf-8 -*-
# business/app_system.py

from sanic.log import logger
from sqlalchemy import select

from model.model_result import DataResult
from model.models import AppSystem
from business.common_func import (
    get_app_system_owner,
    get_app_system_deploy_manner,
)


async def get_app_system(request):
    """
    获取应用系统列表
    """
    data_result = DataResult()
    session = request.ctx.session
    try:
        app_sys_list = []
        async with session.begin():
            query_app_sys = select(AppSystem).where(AppSystem.is_deleted == 0)
            result = await session.execute(query_app_sys)
            app_sys_objs = result.scalars().all()
            app_sys_list = [v.to_dict() for v in app_sys_objs]
            logger.debug(f"get app_system: {app_sys_list}")
        data_result.data["items"] = app_sys_list
        data_result.message = "获取应用系统列表成功"
    except Exception as ex:
        data_result.status = False
        data_result.code = 400
        data_result.message = "获取应用系统列表失败"
        logger.exception(ex)
    return data_result


async def get_app_system_detail_by_id(app_system_id, request):
    """
    根据ID查询应用系统详情
    """
    if not app_system_id:
        raise Exception('缺少应用系统ID(app_system_id)参数值!')
    data_result = DataResult()
    session = request.ctx.session
    try:
        app_sys_info = {}
        async with session.begin():
            query_app_sys = select(
                AppSystem
            ).where(
                AppSystem.app_system_id == app_system_id,
                AppSystem.is_deleted == 0
            )
            result = await session.execute(query_app_sys)
            app_sys_obj = result.scalar()
            if app_sys_obj:
                app_sys_info = app_sys_obj.to_dict()

        # 查询应用负责人信息
        app_sys_info['app_sys_owner'] = await get_app_system_owner(session, app_system_id)
        # 查询应用部署方式
        app_sys_info['app_deploy_manner'] = await get_app_system_deploy_manner(session, app_system_id)
        logger.debug(f"get app_system info by id {app_system_id}, res: {app_sys_info}")
        data_result.data = app_sys_info
        data_result.message = "根据应用系统ID查询应用系统详情成功"
    except Exception as ex:
        data_result.status = False
        data_result.code = 400
        data_result.message = "根据应用系统ID查询应用系统详情失败"
        logger.exception(ex)
    return data_result


async def query_app_system_like_name(app_sys_name, request):
    """
    根据应用系统名称模糊查询应用系统列表
    """
    data_result = DataResult()
    session = request.ctx.session
    try:
        app_sys_list = []
        async with session.begin():
            query_app_sys = select(
                AppSystem
            ).where(
                AppSystem.sys_name.like(f"%{app_sys_name}%"),
                AppSystem.is_deleted == 0
            )
            result = await session.execute(query_app_sys)
            app_sys_objs = result.scalars().all()
            app_sys_list = [v.to_dict() for v in app_sys_objs]
            logger.debug(f"query app_system like name {app_sys_name}, res: {app_sys_list}")
        data_result.data = app_sys_list
        data_result.message = "根据应用系统名称模糊查询应用系统列表成功"
    except Exception as ex:
        data_result.status = False
        data_result.code = 400
        data_result.message = "根据应用系统名称模糊查询应用系统列表失败"
        logger.exception(ex)
    return data_result
